package com.spodrum.balloongl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

import org.andengine.entity.Entity;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.util.color.Color;

public class BalloonManager extends Entity 
{
	private static int MAX_BALLOONS = 20;
	private static final Random RNG = new Random();
	
	private ArrayList<Balloon> balloons;
	private BalloonPool balloonPool;
	private float width;
	private float height;
	
	public BalloonManager(float width, float height, ITextureRegion mBalloonTextureRegion)
	{
		this.width = width;
		this.height = height;
		balloons = new ArrayList<Balloon>();
		balloonPool = new BalloonPool(mBalloonTextureRegion);
		initBalloons();
	}
	
	public void initBalloons()
	{
		Balloon balloon = null;
		
		for(int i = 0; i < MAX_BALLOONS; i++ )
		{			
			float rndX = RNG.nextInt((int) (width) );
			float rndY = RNG.nextInt((int) (height/2) );
			
			balloon = balloonPool.obtainPoolItem();
			balloon.setColor(new Color(RNG.nextFloat(), RNG.nextFloat(), RNG.nextFloat(), 0.75f));
			balloon.setVelocity(0, 50 + RNG.nextInt(50));
			balloon.setScale(0.5f + RNG.nextFloat());
			
			if(rndX + balloon.getWidthScaled() > width)
			{
				rndX = width - balloon.getWidthScaled();
			}
			
			balloon.setX(rndX);
			balloon.setY(-rndY);
			balloon.setVisible(true);
			
			balloons.add(balloon);
			attachChild(balloon);
		}
	}
	
	public void popBalloon(Balloon balloon)
	{
		balloon.setVisible(false);
		balloon.detachSelf();
		balloonPool.recyclePoolItem(balloon);
		//balloons.remove(balloon); // Can't do this because of concurrency errors
	}
	
	public ArrayList<Balloon> getBalloons()
	{
		return balloons;
	}
	
	public Iterator<Balloon> getBalloonIterator()
	{
		return balloons.iterator();
	}
}
